package cn.datawin.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import cn.datawin.bean.Form;
import cn.datawin.bean.page.ReqData;
import cn.datawin.bean.page.RespData;

@Service
public class OnlinecService extends BaseService{
	
	
	public Object list(ReqData reqData, String name){
		BasicDBObject query = new BasicDBObject();
		if(StringUtils.isNotEmpty(name)){
			Pattern  pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
			query.append("acc", pattern);
		}
		RespData<List<DBObject>> rows = super.page("onclient", query, reqData);
		return  rows;
	}
	

	public Object liston(ReqData reqData, String type){
		BasicDBObject query = new BasicDBObject();
		if(StringUtils.isNotEmpty(type)){
			Pattern  pattern = Pattern.compile("^.*" + type + ".*$", Pattern.CASE_INSENSITIVE);
			query.append("type", pattern);
		}
		query.append("state", "1");
		RespData<List<DBObject>> rows = super.page("onclient", query, reqData);
		return  rows;
	}
	
	public Object add(Form form) {
		BasicDBObject client = new BasicDBObject();
		client.append("acc", form.getAcc()).append("pwd", form.getPwd()).append("type", form.getType()).append("state", "0");
		super.insert("onclient", client);
		return 1;
	}

	public Object edit(Form form) {
		BasicDBObject client = new BasicDBObject();
		client.append("acc", form.getAcc()).append("pwd", form.getPwd()).append("type", form.getType());
		super.updateByid("onclient", form.getId(), client);
		return 1;
	}
	
	public Object del(String ids) {
		for(String id: ids.split(",")){
			super.deleteById("onclient", id);
		}
		return 1;
	}

	public Object allotclient(String oncid,String tids){
		if(StringUtils.isEmpty(oncid))return 0;
		if(StringUtils.isEmpty(tids))return 0;
		String[] tid = tids.split(",");
		String[] cid = oncid.split(",");
		String[] vps = new String[1];
		vps[0]=cid[0];
		List<ObjectId> list = new ArrayList<ObjectId>();
		for(String id:tid){
			list.add(new ObjectId(id));
		}
		this.updateMultiSingle("task",new BasicDBObject("_id",new BasicDBObject("$in",list)),new BasicDBObject("httpClientid",cid[1]).append("client", vps));
		return 1;
	}
	
}
